package com.freely.ui.activities

import android.app.Activity
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.request.RequestOptions
import com.freely.R
import com.freely.component.BaseRecyclerViewAdapter
import com.freely.component.BaseRecyclerViewAdapter.BindView
import com.freely.component.BaseViewHolder
import com.freely.component.activity.NavigationActivity
import com.freely.data.entities.Group
import com.freely.data.entities.User
import com.freely.ui.util.AppHint
import com.freely.ui.util.ErrorUtil
import com.freely.ui.viewModel.InviteGroupMemberViewModel
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_invite_group_member.*
import okio.ByteString

class InviteGroupMemberActivity : NavigationActivity() {
    private val TAG = "InviteGroupMember"
    lateinit var viewModel: InviteGroupMemberViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_invite_group_member)
        viewModel = ViewModelProviders.of(this).get(InviteGroupMemberViewModel::class.java)
        viewModel.userId = intent.getLongExtra(User.user_id, -1)
        viewModel.groupId = intent.getLongExtra(Group.group_id, -1)
        recycler_view.layoutManager = LinearLayoutManager(this)
        val adapter = object : BaseRecyclerViewAdapter() {
            override fun getItemCount(): Int {
                return viewModel.list.value?.size ?: 0
            }
        }
        adapter.getView {
            var layout = R.layout.item_select_group
            val temp = viewModel.list.value?.get(it)?.value
            if (temp is User) {
                layout = R.layout.item_select_user
            }
            return@getView layout
        }
        val bindView = BindView<BaseViewHolder> { holder, position ->
            val list = viewModel.list.value
            val node = list?.get(position)
            val temp = node?.value
            if (temp is Group) {//群组布局绑定
                val groupName = holder.getView<TextView>(R.id.group_name)
                val checkBox = holder.getView<CheckBox>(R.id.group_arrow)
                groupName.text = temp.groupName
                holder.itemView.setOnClickListener {
                    Log.d(TAG, "onCreate: -----------------------------------------")
                    Log.d(TAG, "onCreate: position = $position")
                    Log.d(TAG, "onCreate: adapterPosition = ${holder.adapterPosition}")
                    Log.d(TAG, "onCreate: oldPosition = ${holder.oldPosition}")
                    Log.d(TAG, "onCreate: layoutPosition = ${holder.layoutPosition}")
                    if (checkBox.isChecked) {
                        checkBox.isChecked = false
                        val userList = node.childNode
                        val startPosition = holder.adapterPosition + 1
                        val size = userList.size
                        for (i in 1..size) {
                            Log.d(TAG, "onCreate: 移除$i")
                            list.removeAt(startPosition)
                        }
                        adapter.notifyItemRangeRemoved(startPosition, size)
                    } else {
                        checkBox.isChecked = true
                        viewModel.loadMemberList(temp.groupId, holder.adapterPosition)
                    }
                }
            } else if (temp is User) {//群成员布局绑定
                val userHeadIcon = holder.getView<ImageView>(R.id.head_icon)
                val userName = holder.getView<TextView>(R.id.user_name)
                userName.text = temp.userName
                holder.itemView.setOnClickListener {
                    val builder = AlertDialog.Builder(this)
                    builder.setTitle(R.string.group_member_invite)
                    builder.setMessage(getString(R.string.invite_hint, temp.userName))
                    builder.setPositiveButton(R.string.yes) { dialog, which ->
                        val group = node.parentNode?.value as Group
                        viewModel.inviteMember(group.groupId, temp.userId)
                        dialog.dismiss()
                    }
                    builder.setNegativeButton(R.string.no) { dialog, which ->
                        dialog.dismiss()
                    }
                    builder.show()
                }
                val single = Single.create<RequestBuilder<Drawable>> {
                    val builder = Glide.with(this@InviteGroupMemberActivity)
                            .load(ByteString.decodeBase64(temp.userImage)?.toByteArray())
                            .apply(RequestOptions.circleCropTransform())
                    it.onSuccess(builder)
                }.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.computation())

                val disposable = single.subscribe({
                    it.into(userHeadIcon)
                }, { ErrorUtil.errorHint(it) })

                register(disposable)
            }
        }
        adapter.onBindView<BaseRecyclerViewAdapter>(bindView)
        viewModel.list.observe(this, Observer {
            adapter.notifyDataSetChanged()
        })
        viewModel.changeList.observe(this, Observer {
            val node = viewModel.list.value?.get(it)
            if (node != null) {
                val startPosition = it + 1
                val size = node.childNode.size
                adapter.notifyItemRangeInserted(startPosition, size)
            }
        })
        viewModel.inviteResult.observe(this, Observer {
            var hint = getString(R.string.invite_failter)
            if (it) {
                hint = getString(R.string.invite_success)
            }
            AppHint.showToast(hint)
        })
        recycler_view.adapter = adapter
        viewModel.loadGroupList(viewModel.userId)
    }

    companion object {
        fun startActivity(activity: Activity, userId: Long, groupId: Long) {
            val intent = Intent(activity, InviteGroupMemberActivity::class.java)
            intent.putExtra(User.user_id, userId)
            intent.putExtra(Group.group_id, groupId)
            activity.startActivity(intent)
        }
    }
}
